import 'package:flutter/material.dart';

//封装图片加载控件，增加图片加载失败时加载默认图片
class ImageWidget extends StatefulWidget {
  final String url;
  final double? width;
  final double? height;
  final String defaultImage;

  const ImageWidget({
    Key? key,
    required this.url, 
    this.width, 
    this.height, 
    this.defaultImage = "assets/images/flutter.jpg"
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _StateImageWidget();
  }
}

class _StateImageWidget extends State<ImageWidget> {
  late Image _image;

  @override
  void initState() {
    super.initState();
    
    _image = Image.network(
      widget.url,
      width: widget.width,
      height: widget.height,
    );

    // 获取图片数据流
    var resolve = _image.image.resolve(ImageConfiguration.empty);

    // 监听图片数据流
    resolve.addListener(ImageStreamListener((image, synchronousCall) { 
      // 网络图片加载成功
    }, onError: (dynamic exception, StackTrace? stackTrace) {
      // 加载网络图片失败时，加载本地图片
      if (mounted) {
        setState(() {
          _image = Image.asset(
            widget.defaultImage,
            width: widget.width,
            height: widget.height,
          );
        });
      }
    }));
  }

  @override
  Widget build(BuildContext context) {
    return _image;
  }
}
